package com.agentframework.examples.jinhua;

import com.agentframework.core.agent.Agent;
import com.agentframework.core.annotation.Action;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;

import java.util.Set;

/**
 * 开启新一轮游戏动作，负责发牌并通知第一个玩家开始行动
 * @author wangjun
 */
@Action(name = "start_new_round")
public class StartNewRoundAction extends JinhuaDealerAction {

    public StartNewRoundAction(JinhuaTool jinhuaTool) {
        super("start_new_round", jinhuaTool);
    }
    
    @Override
    protected String getFormatInstruction() {
        return """
            你需要开启新一轮游戏，请必须且只能返回如下JSON格式：
            {
                "round": "当前轮次",
                "message": "新一轮游戏开始，已发牌",
                "sendTo": "第一个行动的玩家id"
            }
            
            例如：
            {
                "round": "1",
                "message": "第1轮游戏开始，已发牌",
                "sendTo": "玩家ID（例如：e9fc1d4d）"
            }
            特别注意:
                需要顺序指引所有玩家执行操作
            """;
    }

    @Override
    protected void doHandleResponseMessage(Message message, Object response) {
        var startNewRoundResp = (StartNewRoundResp) response;

        String round = startNewRoundResp.round();
        String messageContent = startNewRoundResp.message();
        String sendTo = startNewRoundResp.sendTo();

        // 通知所有玩家游戏开始
        Message roundStartMessage = new UserMessage(messageContent);
        roundStartMessage.getMetadata().put(Agent.SEND_TO, getPlayerIds());
        roundStartMessage.getMetadata().put(Agent.VIEW_TO, getPlayerIds());
        publishMessage(roundStartMessage);

        // 通知第一个玩家开始行动
        Message firstPlayerMessage = new UserMessage(String.format("轮到玩家%s说话", sendTo));
        firstPlayerMessage.getMetadata().put(Agent.SEND_TO, Set.of(sendTo));
        publishMessage(firstPlayerMessage);

        logger.debug("第{}轮游戏开始，第一个行动的玩家是: {}", round, sendTo);
    }

    @Override
    protected Class<?> getResponseType() {
        return StartNewRoundResp.class;
    }

    record StartNewRoundResp(String round, String message, String sendTo) {

    }

}